<template>
  <div class="order-list">
    <div class="page-header">
      <h2>业务订单</h2>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        创建订单
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select
            v-model="searchForm.orderSubType"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="案件委托" :value="1" />
            <el-option label="法务订单" :value="2" />
            <el-option label="法务专项" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="searchForm.approvalStatus"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <el-option label="待审核" :value="0" />
            <el-option label="审核中" :value="1" />
            <el-option label="审核通过" :value="2" />
            <el-option label="审核拒绝" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="交付状态">
          <el-select
            v-model="searchForm.deliveryStatus"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <el-option label="待交付" :value="0" />
            <el-option label="交付中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #409eff">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">总订单数</div>
              <div class="stat-value">{{ stats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #67c23a">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">已通过</div>
              <div class="stat-value">{{ stats.approved }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #e6a23c">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">审核中</div>
              <div class="stat-value">{{ stats.pending }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #f56c6c">
              <el-icon><CloseBold /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">已拒绝/取消</div>
              <div class="stat-value">{{ stats.rejected }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="order_no" label="订单编号" min-width="150" />
        <el-table-column prop="customer_name" label="客户名称" min-width="150" />
        <el-table-column prop="order_type_name" label="订单类型" width="120" />
        <el-table-column prop="order_sub_type" label="子类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.order_sub_type === 1" type="danger">案件委托</el-tag>
            <el-tag v-else-if="scope.row.order_sub_type === 2" type="warning">法务订单</el-tag>
            <el-tag v-else type="primary">法务专项</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="订单金额" width="120">
          <template #default="scope">￥{{ scope.row.total_amount }}</template>
        </el-table-column>
        <el-table-column prop="paid_amount" label="已付金额" width="120">
          <template #default="scope">￥{{ scope.row.paid_amount }}</template>
        </el-table-column>
        <el-table-column prop="approval_status" label="审核状态" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.approval_status === 0" type="info">待审核</el-tag>
            <el-tag v-else-if="scope.row.approval_status === 1" type="warning">审核中</el-tag>
            <el-tag v-else-if="scope.row.approval_status === 2" type="success">审核通过</el-tag>
            <el-tag v-else-if="scope.row.approval_status === 3" type="danger">审核拒绝</el-tag>
            <el-tag v-else type="danger">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="delivery_status" label="交付状态" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.delivery_status === 0" type="info">待交付</el-tag>
            <el-tag v-else-if="scope.row.delivery_status === 1" type="warning">交付中</el-tag>
            <el-tag v-else type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="signer_name" label="签约人" width="100" />
        <el-table-column prop="create_time" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="text" @click.stop="handleView(scope.row)">查看</el-button>
            <el-button
              type="text"
              @click.stop="handleSubmit(scope.row)"
              v-if="scope.row.approval_status === 0"
            >
              提交审核
            </el-button>
            <el-button
              type="text"
              @click.stop="handleCancel(scope.row)"
              v-if="scope.row.approval_status === 0 || scope.row.approval_status === 1"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="900px">
      <el-descriptions :column="2" border v-if="currentOrder">
        <el-descriptions-item label="订单编号">{{ currentOrder.order_no }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">
          {{ currentOrder.customer_name }}
        </el-descriptions-item>
        <el-descriptions-item label="订单类型">
          {{ currentOrder.order_type_name }}
        </el-descriptions-item>
        <el-descriptions-item label="子类型">
          <el-tag v-if="currentOrder.order_sub_type === 1" type="danger">案件委托</el-tag>
          <el-tag v-else-if="currentOrder.order_sub_type === 2" type="warning">法务订单</el-tag>
          <el-tag v-else type="primary">法务专项</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单金额">
          ￥{{ currentOrder.total_amount }}
        </el-descriptions-item>
        <el-descriptions-item label="已付金额">
          ￥{{ currentOrder.paid_amount }}
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag v-if="currentOrder.approval_status === 0" type="info">待审核</el-tag>
          <el-tag v-else-if="currentOrder.approval_status === 1" type="warning">审核中</el-tag>
          <el-tag v-else-if="currentOrder.approval_status === 2" type="success">审核通过</el-tag>
          <el-tag v-else-if="currentOrder.approval_status === 3" type="danger">审核拒绝</el-tag>
          <el-tag v-else type="danger">已取消</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="交付状态">
          <el-tag v-if="currentOrder.delivery_status === 0" type="info">待交付</el-tag>
          <el-tag v-else-if="currentOrder.delivery_status === 1" type="warning">交付中</el-tag>
          <el-tag v-else type="success">已完成</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="签约人">{{ currentOrder.signer_name }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(currentOrder.create_time) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 财务记录 -->
      <div v-if="currentOrder?.finance_records?.length" class="section">
        <h3>财务记录</h3>
        <el-table :data="currentOrder.finance_records" stripe>
          <el-table-column prop="received_amount" label="到账金额" width="120">
            <template #default="scope">￥{{ scope.row.received_amount }}</template>
          </el-table-column>
          <el-table-column prop="payment_type" label="收款类型" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.payment_type === 1" type="primary">合同应收款</el-tag>
              <el-tag v-else type="warning">后期应收款</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="payment_method" label="收款方式" width="120">
            <template #default="scope">
              {{ getPaymentMethodText(scope.row.payment_method) }}
            </template>
          </el-table-column>
          <el-table-column prop="verification_status" label="核实状态" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.verification_status === 0" type="info">未核实</el-tag>
              <el-tag v-else type="success">已核实</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 合同归档信息 -->
      <div v-if="currentOrder?.contract_archive" class="section">
        <h3>合同归档</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="合同编号">
            {{ currentOrder.contract_archive.contract_no }}
          </el-descriptions-item>
          <el-descriptions-item label="归档状态">
            <el-tag v-if="currentOrder.contract_archive.archive_status === 0" type="info">
              未归档
            </el-tag>
            <el-tag v-else-if="currentOrder.contract_archive.archive_status === 1" type="success">
              已归档
            </el-tag>
            <el-tag v-else type="danger">审核驳回</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 工单信息 -->
      <div v-if="currentOrder?.work_order" class="section">
        <h3>工单信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单编号">
            {{ currentOrder.work_order.work_order_no }}
          </el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag v-if="currentOrder.work_order.status === 1" type="info">待分配</el-tag>
            <el-tag v-else-if="currentOrder.work_order.status === 2" type="warning">进行中</el-tag>
            <el-tag v-else-if="currentOrder.work_order.status === 3" type="success">已完成</el-tag>
            <el-tag v-else type="danger">已取消</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { Plus, Document, Check, Timer, CloseBold } from '@element-plus/icons-vue'

  const router = useRouter()

  // 类型定义
  interface FinanceRecord {
    received_amount: number
    payment_type: number
    payment_method: number
    verification_status: number
  }

  interface ContractArchive {
    contract_no: string
    archive_status: number
  }

  interface WorkOrder {
    work_order_no: string
    status: number
  }

  // 使用通用的Order类型
  type Order = any

  // 搜索表单
  const searchForm = reactive({
    customerName: '',
    orderSubType: '',
    approvalStatus: '',
    deliveryStatus: '',
  })

  // 表格数据
  const tableData = ref<Order[]>([])
  const loading = ref(false)
  // 统计数据
  const stats = reactive({
    total: 0,
    approved: 0,
    pending: 0,
    rejected: 0,
  })

  // 分页
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0,
  })

  // 详情对话框
  const detailDialogVisible = ref(false)
  const currentOrder = ref<Order | null>(null)

  // 初始化
  onMounted(() => {
    fetchData()
    fetchStats()
  })

  // 获取统计数据
  const fetchStats = async () => {
    try {
      // 调用CRM概览统计API获取真实数据
      const { statsApi } = await import('@/api/crm')
      const res = await statsApi.dashboard()

      if (res.code === 0 && res.data) {
        // 从概览数据中提取订单统计信息
        // 注意：totalOrders 是订单总数，而不是 totalCustomers（客户数）
        stats.total = res.data.totalOrders || 0
        stats.pending = res.data.pendingOrders || 0
        stats.approved = res.data.approvedOrders || 0
        stats.rejected = res.data.rejectedOrders || 0
      } else {
        // 如果API失败，设置为0
        stats.total = 0
        stats.pending = 0
        stats.approved = 0
        stats.rejected = 0
      }
    } catch (error) {
      console.error('获取统计数据失败:', error)
      // 出错时设置为0
      stats.total = 0
      stats.pending = 0
      stats.approved = 0
      stats.rejected = 0
    }
  }

  // 获取表格数据
  const fetchData = async () => {
    loading.value = true
    try {
      const { getOrderList } = await import('@/api/order')
      const params: any = {
        page: pagination.page,
        limit: pagination.pageSize,
      }
      if (searchForm.customerName) params.customer_name = searchForm.customerName
      if (searchForm.orderSubType) params.order_sub_type = searchForm.orderSubType
      if (searchForm.approvalStatus !== '') params.approval_status = searchForm.approvalStatus
      if (searchForm.deliveryStatus !== '') params.delivery_status = searchForm.deliveryStatus

      const res: any = await getOrderList(params)
      if (res.code === 0) {
        tableData.value = res.data.list || []
        pagination.total = res.data.total || 0
      } else {
        ElMessage.error(res.msg || '获取数据失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    fetchData()
  }

  // 重置
  const handleReset = () => {
    searchForm.customerName = ''
    searchForm.orderSubType = ''
    searchForm.approvalStatus = ''
    searchForm.deliveryStatus = ''
    handleSearch()
  }

  // 创建订单
  const handleCreate = () => {
    // 修改为正确的订单创建路由
    router.push('/crm/order/create')
  }

  // 查看详情
  const handleView = (row: Order) => {
    detailDialogVisible.value = true
    currentOrder.value = row
  }

  // 提交审核
  const handleSubmit = async (row: Order) => {
    try {
      await ElMessageBox.confirm('确定要提交审核吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      const { submitOrderForApproval } = await import('@/api/order')
      const res = await submitOrderForApproval(row.id)
      // 修复：正确访问Axios响应对象的data属性
      if (res.data.code === 0) {
        ElMessage.success('提交成功')
        fetchData()
      } else {
        ElMessage.error(res.data.msg || '提交失败')
      }
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 取消订单
  const handleCancel = async (row: Order) => {
    try {
      await ElMessageBox.confirm('确定要取消此订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      const { cancelOrder } = await import('@/api/order')
      const res = await cancelOrder(row.id)
      // 修复：正确访问Axios响应对象的data属性
      if (res.data.code === 0) {
        ElMessage.success('取消成功')
        fetchData()
      } else {
        ElMessage.error(res.data.msg || '取消失败')
      }
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 行点击
  const handleRowClick = (row: Order) => {
    // 修改为正确的路由路径
    router.push(`/crm/orders/${row.id}`)
  }

  // 分页
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val
    fetchData()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    fetchData()
  }

  // 格式化日期
  const formatDateTime = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(
      typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000
    )
    return date.toLocaleString()
  }

  // 获取支付方式文本
  const getPaymentMethodText = (method: number) => {
    const map: Record<number, string> = {
      1: '银行转账',
      2: '支付宝',
      3: '微信',
      4: '现金',
      5: '其他',
    }
    return map[method] || '未知'
  }
</script>

<style lang="scss" scoped>
  .order-list {
    padding: 20px;

    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    .filter-card {
      margin-bottom: 20px;
    }

    .stats-row {
      margin-bottom: 20px;
    }

    .stat-item {
      display: flex;
      align-items: center;

      .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        color: #fff;
        font-size: 24px;
      }

      .stat-content {
        flex: 1;

        .stat-label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 4px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
        }
      }
    }

    .table-card {
      margin-bottom: 20px;

      .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }
    }

    .section {
      margin-top: 20px;

      h3 {
        margin-bottom: 15px;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
</style>
